<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }}条</span>
        </template>
        <template #right>
          <el-button v-if="$checkPoint('daoru')" type="warning" size="small" @click="daoruFN">excel导入</el-button>
          <el-button v-if="$checkPoint('daochu')" type="danger" size="small" :loading="shouloading" @click="daochuFn">excel导出</el-button>
          <el-button v-if="$checkPoint('addyg')" type="primary" size="small" @click="addFN">新增员工</el-button>
        </template>
      </page-tools>
      <div v-show="daorushow==true">
        <el-button type="primary" icon="el-icon-arrow-left" @click.native="daoruBtn">上一页</el-button>
        <UploadExcel :on-success="handleSuccess" />
      </div>
      <div v-show="daorushow==false">
        <el-card style="margin-top: 10px;">
          <el-table v-loading="loading" border :data="list" :default-sort="{prop: 'workNumber'}">
            <el-table-column label="序号" type="index" />
            <el-table-column label="姓名" prop="username" />
            <el-table-column label="头像" prop="staffPhoto">
              <template slot-scope="scope">
                <!-- <img :src="scope.row.staffPhoto" alt="" class="imgwid"> -->
                <imgcomp :img="scope.row.staffPhoto" />
                <!-- <el-image
                  style="width: 100px; height: 100px"
                  :src="scope.row.staffPhoto"
                  :fit="fit"
                /> -->
              </template>
            </el-table-column>
            <el-table-column label="工号" prop="workNumber" />
            <el-table-column label="聘用形式" prop="formOfEmployment">
              <template slot-scope="scope">
                {{ formatEmployment(scope.row.formOfEmployment) }}
              </template>
            </el-table-column>
            <el-table-column label="部门" prop="departmentName" />
            <el-table-column label="入职时间" prop="timeOfEntry" width="120">
              <template slot-scope="scope">
                {{ Time(scope.row) }}
              </template>
            </el-table-column>
            <el-table-column label="账户状态" prop="enableState" />
            <el-table-column label="操作" fixed="right" width="280">
              <template slot-scope="scope">
                <el-button type="text" size="small" @click="$router.push('/employees/detail?id='+scope.row.id)">查看</el-button>
                <el-button type="text" size="small" @click="hEditRole(scope.row.id)">分配</el-button>

                <el-button type="text" size="small" @click="hDel(scope.row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        <!-- 分页组件 -->

        </el-card>
        <div style="height: 60px; margin-top: 10px">
          <el-pagination
            :total="total"
            :current-page="params.page"
            :page-size="params.pageSize"
            layout="prev, pager, next"
            @current-change="currentchange"
          />
        </div>
      </div>
      <el-dialog title="新增员工" :visible.sync="showDialog" :close-on-click-modal="false" @close="close">
        <Addemplay
          ref="addEmploy"
          @Cancleclose="showDialog=false"
          @closesx="closesx"
        />
      </el-dialog>
      <el-dialog :visible.sync="showDialogRole" :close-on-click-modal="false" :close-on-press-escape="false" @close="closes">
        <Digg ref="dig" :currentid="currentid" @close="closes" />
      </el-dialog>
    </div>
  </div>
</template>
<script>
// import Daoru from './daoru'
import Digg from '../setting/comopen/dig'
import { transExcelHander } from '@/utils/wenjiandaoru'
import { reqGetEmployeeList, delEmployee, importEmployee } from '@/api/employess'
// import { reqGetEmployeeList } from '@/api/employess'
import EmployeeEnum from '../../components/枚举/constant/employees'
import Addemplay from './addEmployee'
const hireType = {}
EmployeeEnum.hireType.forEach(item => {
  hireType[item.id] = item.value
})
export default {
  name: 'Employees',
  components: {
    Addemplay,
    Digg
    // Daoru
  },

  data() {
    return {
      currentid: '', // 当前点击的id
      showDialogRole: false,
      shouloading: false, // 转圈圈
      daorushow: false,
      showDialog: false, // 子组件弹出层
      shuju: null,
      list: [],
      params: {
        page: 1, // 当前页
        Size: 10 // 每页条数
      },
      total: 0, // 总数
      loading: false

    }
  },

  mounted() {
    this.reqGetEmployeeList()
  },
  methods: {
    closes() {
      this.showDialogRole = false
      this.$refs.dig.getgetUserDetailById()
    },
    hEditRole(id) {
      // console.log(row.id)
      this.currentid = id
      // console.log(1)
      // console.log(1)
      this.showDialogRole = true
      console.log(id)
      // console.log(this.showDialogRole)
    },
    Time(i) {
      // console.log(i.timeOfEntry)
      const list = i.timeOfEntry.split('T')[0].split('-')
      // const str = i.timeOfEntry.substring(0, 9).split('')
      // console.log(str)
      // console.log(list[0] + '年' + list[1] + '月' + list[2] + '日')
      return list[0] + '年' + list[1] + '月' + list[2] + '日'
    },
    // 文件导出
    transData(arr) {
      // 把formOfEmployment中的1改成正式， 2改成非正式
      arr.forEach(item => {
        if (item.formOfEmployment) {
          // 1 --> 正式
          // 2 --> 非正式
          item.formOfEmployment = hireType[item.formOfEmployment]
        }
      })
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      // 取出数组中第一个元素，来根据key生成对应的中文
      const first = arr[0]
      const header = Object.keys(first).map(item => map[item])
      // console.log('表头是', header)
      const data = arr.map(obj => {
        return Object.values(obj)
      })
      // console.log('数据是', data)
      return { header, data }
    },
    daochuFn() {
      // 点击导出
      import('@/utils/Export2Excel').then(async excel => {
        // 1. 发请求，获取当前页的数据
        this.shouloading = true
        const rs = await reqGetEmployeeList(this.params)
        // console.log('从后端获取的员工列表是', rs.data.rows)

        // 2. 修改一下数据格式，以便导出
        const { header, data } = this.transData(rs.data.rows)
        // 3. 导出
        excel.export_json_to_excel({
          header, // 表头 必填
          data,
          filename: 'test-export-excel',
          autoWidth: true,
          bookType: 'xlsx'
        })
        this.shouloading = false
      })
    },
    async  handleSuccess({ results, header }) {
      // console.log('从当前excel文件中读出的内容是', results, header)
      this.tableData = results
      this.tableHeader = header
      await transExcelHander(results)
      try {
        await importEmployee(transExcelHander(results))
        this.$message.success('操作成功')
        this.daorushow = false
        this.reqGetEmployeeList()
      } catch (re) {
        // console.log(re)
        this.$message.error(re.message)
      }
      // this.$message.success(re.message)
      // console.log(re)
    },
    // transExcelHander(results) {
    //   const userRelations = {
    //     '入职日期': 'timeOfEntry',
    //     '手机号': 'mobile',
    //     '姓名': 'username',
    //     '转正日期': 'correctionTime',
    //     '工号': 'workNumber'
    //   }
    //   const newArr = results.map(item => {
    //     const userInfo = {}
    //     for (const key in item) {
    //       const newKey = userRelations[key]
    //       userInfo[newKey] = item[key]
    //       if (['correctionTime', 'timeOfEntry'].includes(newKey)) {
    //         // 需要对key对应的value做时间处理
    //         // 严格来讲需要使用与excel插件配套的时间处理函数 处理成标准的时间Date格式
    //         // 后端接口才能识别
    //         userInfo[newKey] = new Date(formatDate(item[key]))
    //       }
    //     }
    //     return userInfo
    //   })
    //   console.log(newArr)
    //   return newArr
    // },
    daoruBtn() {
      this.daorushow = false
    },
    daoruFN() {
      this.daorushow = true
    },
    close() {
      // console.log(2)
      this.show = true
      this.showDialog = false
      // 找到子组件,执行其中的重置表单
      // console.log(11111)
      // this.$refs.addEmploy.abc()
      // console.log(111111111)
      this.$refs.addEmploy.clearfrom()
      // console.log(11111111111111)
    },
    // 子组件通知父组件更新列表关闭弹窗
    closesx() {
      // console.log(1)
      this.reqGetEmployeeList()
      this.showDialog = false
    },
    addFN() {
      if (this.daorushow) {
        this.$message.success('返回第一页添加')
        this.daorushow = false
      }
      this.showDialog = true
    },
    formatEmployment(val) {
      const map = {}
      EmployeeEnum.hireType.forEach(item => { map[item.id] = item.value })
      // console.log(val, map)
      return map[val]
    },
    currentchange(i) {
      this.params.page = i
      this.reqGetEmployeeList()
    },
    async reqGetEmployeeList() {
      // this.loading = true
      const data = await reqGetEmployeeList(this.params)
      console.log(data.data.rows)
      // eslint-disable-next-line no-prototype-builtins

      // console.log(data.data)
      this.list = data.data.rows
      this.total = data.data.total

      // console.log(data)
    },
    hDel(id) {
      this.$confirm('你确定要删除吗', '温馨提示').then(async() => {
        // console.log(1)
        await delEmployee(id)
        // console.log(2)
        if (this.list.length === 1) {
          // console.log(3)
          this.params.page--
          // console.log(2)
        }
        this.reqGetEmployeeList()
        this.$message.success('删除角色成功')
      }).catch(res => {
        // console.dir(res)
        this.$message.error(res.message)
        // console.log(res)
      })
    }
  }
}
</script>
<style scoped>
.juzhon{
 text-align: center;
}
.imgwid{
  width: 100%;
}
</style>

